package BeenChina.PM.Action;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap; 
import java.util.List;
import java.util.Map; 

import javax.jws.WebParam.Mode;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.ui.Model;

import net.sf.json.JSONArray;
 
import BeenChina.PM.Model.ModelCaseRankInfo; 
import BeenChina.PM.Model.ModelUser;
import BeenChina.PM.Service.ServiceFactory;
import BeenChina.PM.Util.EncodeDownLoadFileName;
import BeenChina.PM.Util.ExportInfo;
import BeenChina.PM.Util.ExportToExcel;
import BeenChina.PM.Util.xmlSerializer;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class CaseRankInfoQueryAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	private Map<String, Object> tableData;
	private InputStream excelStream;
	private String fileName;
	private static String EXPORTID = "131";
	private boolean exportExcel;
	private static final Log log = LogFactory.getLog(CaseRankInfoQueryAction.class);
 

	public boolean isExportExcel() {
		return exportExcel;
	}

	public InputStream getExcelStream() {
		return excelStream;
	}

	public void setExcelStream(InputStream excelStream) {
		this.excelStream = excelStream;
	}

	public String getFileName() throws UnsupportedEncodingException {
		ServletActionContext.getResponse().setHeader("charset", "UTF-8");
		fileName = EncodeDownLoadFileName.encode(
				ServletActionContext.getRequest(), fileName);
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
  

	public Map<String, Object> getTableData() {
		return tableData;
	}

	
	
	@Override
	public String execute() {
		ModelUser user = (ModelUser) ActionContext.getContext().getSession()
				.get("user");
		if (user != null)
			exportExcel = user.concatPermission(EXPORTID);
		return "load";
	}

	public List<ModelCaseRankInfo> getBaseInfos() throws Exception {
		try {
				return ServiceFactory.getInstance()
						.getBaseInfoService().selectCaseRankInfo();
			 
		} catch (Exception exp) {
			throw exp;
		}
	}
 

	public String refreshData() throws Exception {

		List<ModelCaseRankInfo> baseInfos = getBaseInfos(); 

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("CaseRankInfoTable", getBaseInfoTable(baseInfos));
	 

	 
		tableData = map;
		return ActionSupport.SUCCESS;
	}

   
 
	private JSONArray getBaseInfoTable(List<ModelCaseRankInfo> list) {

		JSONArray mapTable = new JSONArray();
		if (list == null || list.size() == 0) {
			return mapTable;
		}

		JSONArray jsonTittle = new JSONArray();
		jsonTittle.add("案件"); 
		
		
		String firstItem = list.get(0).getRankID();

		for (ModelCaseRankInfo model : list) {
			String nextItem = model.getRankID();
			if (!nextItem.equals(firstItem)) {

				 
				if  ( ! jsonTittle.contains(firstItem)  ){
					jsonTittle.add(firstItem);
					firstItem = nextItem;
				}

			}
		}
		if  ( ! jsonTittle.contains(firstItem)  ){
			jsonTittle.add(firstItem);			
		}
		jsonTittle.add("合計");
		
		mapTable.add(jsonTittle);
		
		firstItem = list.get(0).getRankID();
		
		List<ModelCaseRankInfo> resultHeader = new ArrayList<ModelCaseRankInfo>();
		for (int i = 0; i < list.size(); i++) {
			ModelCaseRankInfo model = list.get(i);

			if (model.getRankID().equals(firstItem)) {
				resultHeader.add(model);
			}
		}

		for (int i = 0; i < resultHeader.size(); i++) {
			ModelCaseRankInfo modelH = resultHeader.get(i);

			JSONArray json = new JSONArray();

			json.add(modelH.getCaseName());
			
			Integer empSum = 0;
			
			for (int k = 1; k < jsonTittle .size() - 1 ; k++) {
			
				String rankid = jsonTittle.getString(k);
				
				for (int j = 0; j < list.size(); j++) {
					 
					ModelCaseRankInfo model = list.get(j);
					if (modelH.getCaseName().equals(model.getCaseName()) &&
						model.getRankID().equals(rankid)	 ) {
			
						empSum += model.getEmpCount();
						json.add(model.getEmpCount());
	
					}
				}
			
			}
			
			
			json.add(empSum);
			mapTable.add(json);
		}

		return mapTable;
	}

	 
	 public String export() throws Exception {
		
		 try {
			 
			 
			String	excelfile = "CaseRankInfoQuery.xls";
			String	xmlfile = "CaseRankInfoQuery.xml";
			 
			//begin
			String file = ServletActionContext.getServletContext().getRealPath(
					"WEB-INF/excel/" + excelfile);

			List<ModelCaseRankInfo> baseInfos = getBaseInfos();
			 

			Map<String, JSONArray> map = new HashMap<String, JSONArray>();
			map.put("権限付与情報", getBaseInfoTable(baseInfos));
			  
		 

			ByteArrayOutputStream out = new ByteArrayOutputStream();
			this.setFileName("権限付与情報"  );
			
			String infoFile = ServletActionContext.getServletContext()
					.getRealPath("WEB-INF/excel/" +xmlfile);
			List<ExportInfo> infoList = (new xmlSerializer<List<ExportInfo>>())
					.read(infoFile);

			ExportToExcel.export(file, map, infoList, out);

			setExcelStream(new ByteArrayInputStream(out.toByteArray()));
			out.close();

			return ActionSupport.SUCCESS;
		} catch (Exception exp) {
			log.error(exp);
			return ActionSupport.ERROR;
		} 
 }

}
